package cn.geekyspace.scanhive.domain.service.impl;

import cn.geekyspace.scanhive.application.dto.query.QueryData;
import cn.geekyspace.scanhive.domain.entity.CleaningData;
import cn.geekyspace.scanhive.domain.mapper.CleaningDataMapper;
import cn.geekyspace.scanhive.domain.service.CleaningDataService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class CleaningDataServiceImpl extends ServiceImpl<CleaningDataMapper, CleaningData> implements CleaningDataService {

    @Override
    public CleaningData saveQrCode(String qrCode, String operatorUser) {
        CleaningData cleaningData = new CleaningData(qrCode, operatorUser);
        this.save(cleaningData);
        return cleaningData;
    }

    @Override
    public void updateByPlcData(CleaningData data) {
        data.setPlcDataReturnTime(LocalDateTime.now());
        this.updateById(data);
    }

    @Override
    public Page<CleaningData> pageQuery(QueryData query) {
        Page<CleaningData> pageParam = new Page<>(query.getCurrent(), query.getSize());

        LambdaQueryWrapper<CleaningData> queryWrapper = new LambdaQueryWrapper<CleaningData>()
                .eq(StringUtils.hasText(query.getQrCode()), CleaningData::getQrCode, query.getQrCode())
                .ge(query.getQrCodeScanTimeStart() != null, CleaningData::getQrCodeScanTime, query.getQrCodeScanTimeStart())
                .le(query.getQrCodeScanTimeEnd() != null, CleaningData::getQrCodeScanTime, query.getQrCodeScanTimeEnd())
                .orderByDesc(CleaningData::getQrCodeScanTime)
                .orderByDesc(CleaningData::getId);
        return baseMapper.selectPage(pageParam, queryWrapper);
    }

}
